package org.ring.common.transport;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.io.InputStream;

/**
 * @since 2024-07-15 23:22
 */
public class ByteBufInputStream extends InputStream {

    private final ByteBuf buf;
    private final int startIndex;
    private final int endIndex;

    public ByteBufInputStream(ByteBuf buf) {
        this(buf,buf.readableBytes());
    }

    public ByteBufInputStream(ByteBuf buf,  int len) {
        if (buf == null) {
            throw new NullPointerException("buffer");
        }
        if (len < 0) {
            throw new IllegalArgumentException("length: " + len);
        }
        if (len > buf.readableBytes()) {
            throw new IndexOutOfBoundsException();
        }
        this.buf = buf;
        this.startIndex = buf.readerIndex();
        this.endIndex = startIndex + len;
        buf.markReaderIndex();
    }

    public int readBytes() {
        return buf.readerIndex() - startIndex;
    }

    @Override
    public int read() throws IOException {
        if (!buf.isReadable()) {
            return -1;
        }
        return buf.readByte() & 0xff;
    }



    @Override
    public int available() throws IOException {
        return endIndex - buf.readerIndex();
    }

    @Override
    public synchronized void mark(int readLimit) {
        buf.markReaderIndex();
    }

    @Override
    public boolean markSupported() {
        return true;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int available = available();
        if (available == 0) {
            return -1;
        }

        len = Math.min(available, len);
        buf.readBytes(b, off, len);
        return len;
    }

    @Override
    public synchronized void reset() throws IOException {
        buf.resetReaderIndex();
    }

    @Override
    public long skip(long n) throws IOException {
        int nBytes = available();
        if(n < nBytes) {
            nBytes = (int)n;
        }
        buf.skipBytes(nBytes);
        return nBytes;

    }

}
